package com.gxb.codebook;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.viewmodel.CreationExtras;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.gxb.codebook.adapter.NotepadAdapter;
import com.gxb.codebook.bean.NotepadBean;
import com.gxb.codebook.database.SQLiteHelper;

import java.util.List;

public class PasswdActivity extends Fragment implements HomeActivity.DataRefreshListener {
    private ListView listView;
    private NotepadAdapter adapter;
    private List<NotepadBean> notepadList;
    private SQLiteHelper dbHelper;
    private Button append_btn;
    private Dialog mDialog;
    private FragmentActivity mActivity;
    private CancellationSignal mCancellationSignal;
    private BroadcastReceiver themeChangeReceiver;
    private LocalBroadcastManager localBroadcastManager;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_passwd, container, false);
        listView = view.findViewById(R.id.listview);
        append_btn = view.findViewById(R.id.append_btn);
        mActivity = getActivity();
        dbHelper = new SQLiteHelper(getContext());
        notepadList = dbHelper.getAllPasswdNotepads();
        adapter = new NotepadAdapter(getContext(), notepadList);
        listView.setAdapter(adapter);
        listView.setDivider(null);

        // 初始化LocalBroadcastManager
        if (mActivity != null) {
            localBroadcastManager = LocalBroadcastManager.getInstance(mActivity);
        }

        // 初始化广播接收器
        initThemeChangeReceiver();

        // 注册广播接收器
        registerThemeChangeReceiver();

        // 设置点击监听器
        listView.setOnItemClickListener((parent, view1, position, id) -> showPasswordDialog(position));
        listView.setOnItemLongClickListener((parent, view1, position, id) -> {
            showDeleteDialog(position);
            return true;
        });
        append_btn.setOnClickListener(v -> append_btn());

        refreshData();
        return view;
    }

    private void initThemeChangeReceiver() {
        themeChangeReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if ("THEME_CHANGED".equals(intent.getAction())) {
                    if (mActivity != null) {
                        mActivity.recreate();
                    }
                }
            }
        };
    }

    private void registerThemeChangeReceiver() {
        if (localBroadcastManager == null || themeChangeReceiver == null) return;

        IntentFilter filter = new IntentFilter("THEME_CHANGED");
        localBroadcastManager.registerReceiver(themeChangeReceiver, filter);
    }

    private void unregisterThemeChangeReceiver() {
        if (localBroadcastManager != null && themeChangeReceiver != null) {
            try {
                localBroadcastManager.unregisterReceiver(themeChangeReceiver);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unregisterThemeChangeReceiver();
    }

    private void showPasswordDialog(int position) {
        mDialog = new Dialog(mActivity);
        mDialog.setContentView(R.layout.passwd_item_layout);
        mDialog.setCancelable(false);

        if (mDialog.getWindow() != null) {
            mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
            int widthInDp = 300;
            int widthInPx = (int) (widthInDp * getResources().getDisplayMetrics().density);
            mDialog.getWindow().setLayout(widthInPx, WindowManager.LayoutParams.WRAP_CONTENT);
        }

        EditText user = mDialog.findViewById(R.id.user);
        EditText name = mDialog.findViewById(R.id.name);
        EditText passwd = mDialog.findViewById(R.id.passwd);
        EditText text = mDialog.findViewById(R.id.text);
        Button user_copy = mDialog.findViewById(R.id.user_copy);
        Button name_copy = mDialog.findViewById(R.id.name_copy);
        Button passwd_copy = mDialog.findViewById(R.id.passwd_copy);
        Button text_copy = mDialog.findViewById(R.id.text_copy);

        user.setText(notepadList.get(position).getUser());
        name.setText(notepadList.get(position).getName());
        passwd.setText(notepadList.get(position).getPasswd());
        text.setText(notepadList.get(position).getText());

        Button outbtn = mDialog.findViewById(R.id.out_btn);
        Button xiugai = mDialog.findViewById(R.id.xiugai_btn);

        outbtn.setOnClickListener(v -> outbtn());

        View[] views = {user_copy, name_copy, passwd_copy, text_copy};
        TextView[] textViews = {user, name, passwd, text};

        for (int i = 0; i < views.length; i++) {
            int finalI = i;
            views[i].setOnClickListener(v -> copyText(textViews[finalI].getText().toString()));
        }

        xiugai.setOnClickListener(v -> xiugais(position));
        mDialog.show();

        // 发送密码对话框显示广播
        if (localBroadcastManager != null) {
            Intent dialogIntent = new Intent("PASSWORD_DIALOG_SHOWN");
            dialogIntent.putExtra("position", position);
            localBroadcastManager.sendBroadcast(dialogIntent);
        }
    }

    private void showDeleteDialog(final int position) {
        mDialog = new Dialog(mActivity);
        mDialog.setContentView(R.layout.delete);
        mDialog.setCancelable(false);

        if (mDialog.getWindow() != null) {
            mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
            int widthInDp = 300;
            int widthInPx = (int) (widthInDp * getResources().getDisplayMetrics().density);
            mDialog.getWindow().setLayout(widthInPx, WindowManager.LayoutParams.WRAP_CONTENT);
        }

        Button outbtn = mDialog.findViewById(R.id.delete_no);
        Button yesbtn = mDialog.findViewById(R.id.delete_yes);

        outbtn.setOnClickListener(v -> {
            mDialog.dismiss();

            // 发送取消删除广播
            if (localBroadcastManager != null) {
                Intent cancelIntent = new Intent("PASSWORD_DELETE_CANCELLED");
                cancelIntent.putExtra("position", position);
                localBroadcastManager.sendBroadcast(cancelIntent);
            }
        });

        yesbtn.setOnClickListener(v -> {
            dbHelper.deletePasswdNotepad(notepadList.get(position).getId());
            refreshData();
            mDialog.dismiss();

            // 发送密码删除成功广播
            if (localBroadcastManager != null) {
                Intent deleteIntent = new Intent("PASSWORD_DELETED");
                deleteIntent.putExtra("position", position);
                localBroadcastManager.sendBroadcast(deleteIntent);
            }
        });

        mDialog.show();

        // 发送删除对话框显示广播
        if (localBroadcastManager != null) {
            Intent dialogIntent = new Intent("DELETE_DIALOG_SHOWN");
            dialogIntent.putExtra("position", position);
            localBroadcastManager.sendBroadcast(dialogIntent);
        }
    }

    private void copyText(String string) {
        ClipboardManager clipboard = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clipData = ClipData.newPlainText("label", string);
        clipboard.setPrimaryClip(clipData);
        Toast.makeText(mActivity, "复制成功", Toast.LENGTH_SHORT).show();

        // 发送文本复制成功广播
        if (localBroadcastManager != null) {
            Intent copyIntent = new Intent("TEXT_COPIED");
            copyIntent.putExtra("text", string);
            localBroadcastManager.sendBroadcast(copyIntent);
        }
    }

    private void append_btn() {
        mDialog = new Dialog(mActivity);
        mDialog.setContentView(R.layout.passwd_item_layout);
        mDialog.setCancelable(false);

        if (mDialog.getWindow() != null) {
            mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
            int widthInDp = 300;
            int widthInPx = (int) (widthInDp * getResources().getDisplayMetrics().density);
            mDialog.getWindow().setLayout(widthInPx, WindowManager.LayoutParams.WRAP_CONTENT);
        }

        Button outbtn = mDialog.findViewById(R.id.out_btn);
        Button xiugai = mDialog.findViewById(R.id.xiugai_btn);

        outbtn.setOnClickListener(v -> outbtn());
        xiugai.setOnClickListener(v -> xiugai());
        mDialog.show();

        // 发送新建密码对话框显示广播
        if (localBroadcastManager != null) {
            Intent dialogIntent = new Intent("NEW_PASSWORD_DIALOG_SHOWN");
            localBroadcastManager.sendBroadcast(dialogIntent);
        }
    }

    private void outbtn() {
        mDialog.dismiss();
        if (mCancellationSignal != null) {
            mCancellationSignal.cancel();
        }

        // 发送对话框关闭广播
        if (localBroadcastManager != null) {
            Intent closeIntent = new Intent("DIALOG_CLOSED");
            localBroadcastManager.sendBroadcast(closeIntent);
        }
    }

    private void xiugais(int position) {
        EditText user = mDialog.findViewById(R.id.user);
        EditText name = mDialog.findViewById(R.id.name);
        EditText passwd = mDialog.findViewById(R.id.passwd);
        EditText text = mDialog.findViewById(R.id.text);

        int id = Integer.parseInt(notepadList.get(position).getId());
        dbHelper.updateNotepad(id, user.getText().toString(), name.getText().toString(),
                passwd.getText().toString(), text.getText().toString());
        refreshData();
        mDialog.dismiss();

        // 发送密码更新成功广播
        if (localBroadcastManager != null) {
            Intent updateIntent = new Intent("PASSWORD_UPDATED");
            updateIntent.putExtra("position", position);
            localBroadcastManager.sendBroadcast(updateIntent);
        }
    }

    private void xiugai() {
        EditText user = mDialog.findViewById(R.id.user);
        EditText name = mDialog.findViewById(R.id.name);
        EditText passwd = mDialog.findViewById(R.id.passwd);
        EditText text = mDialog.findViewById(R.id.text);

        dbHelper.insertNotepad(user.getText().toString(), name.getText().toString(),
                passwd.getText().toString(), text.getText().toString());
        refreshData();
        mDialog.dismiss();

        // 发送新密码添加成功广播
        if (localBroadcastManager != null) {
            Intent addIntent = new Intent("NEW_PASSWORD_ADDED");
            localBroadcastManager.sendBroadcast(addIntent);
        }
    }

    public void refreshData() {
        notepadList = dbHelper.getAllPasswdNotepads();
        adapter.updateData(notepadList);

        // 发送数据刷新广播
        if (localBroadcastManager != null) {
            Intent refreshIntent = new Intent("PASSWORD_DATA_REFRESHED");
            refreshIntent.putExtra("count", notepadList.size());
            localBroadcastManager.sendBroadcast(refreshIntent);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 2) {
            refreshData();
        }
    }

    @NonNull
    @Override
    public CreationExtras getDefaultViewModelCreationExtras() {
        return super.getDefaultViewModelCreationExtras();
    }
}
